package moxl.xpath.parser.types;

import moxl.dom.MoxlAttribute;
import moxl.dom.MoxlElement;
import moxl.dom.MoxlNode;
import moxl.xpath.axes.XPathAxis;

public class NameMatcher implements NodeTestMatcher
{
	private final String pattern;
	private final XPathAxis axis;

	public NameMatcher(XPathAxis axis, String pattern)
	{
		this.axis = axis;
		this.pattern = pattern;
	}

	public boolean matches(MoxlNode node)
	{
		if (axis == XPathAxis.CHILD || axis == XPathAxis.DESCENDANT)
		{
			if (node instanceof MoxlElement)
			{
				if (pattern.equals("*"))
				{
					return true;
				}
				else
				{
					MoxlElement el = (MoxlElement) node;
					return pattern.equals(el.getName().getLocalPart());
				}
			}
			else
			{
				return false;
			}
		}
		else if (axis == XPathAxis.ATTRIBUTE)
		{
			if (node instanceof MoxlAttribute)
			{
				if (pattern.equals("*"))
				{
					return true;
				}
				else
				{
					MoxlAttribute attribute = (MoxlAttribute) node;
					return pattern.equals(attribute.getQName().getLocalPart());
				}
			}
			else
			{
				return false;
			}
		}
		else
		{
			throw new UnsupportedOperationException("Nodes of type " + node.getNodeName() + " are currently unsupported by name tests on the " + axis + " axis");
		}
	}
}
